package com.tianfeng.fenghuotoutiao.ui.activity.AppListActibity;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tianfeng.fenghuotoutiao.R;
import com.tianfeng.fenghuotoutiao.ui.fragment.base.BaseFragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.pm.PackageManager.*;

/**
 * A simple {@link Fragment} subclass.
 */
public class TwoFragment extends BaseFragment {

    @BindView(R.id.rel_list)
    public RecyclerView rel_list;
    @BindView(R.id.iv_test)
    public ImageView iv_test;
    RedpackAdater appListAdater;
    List<Redpackmodel.DataBean> appLists=new ArrayList<>();
    public TwoFragment() {
        // Required empty public constructor
    }




    @Override
    protected View getContentView() {
        return inflatLayout(R.layout.fragment_two);
    }

    @Override
    protected void initData() {
        super.initData();
        requestGetAppList();
    }





    /**
     * 请求小视频地址
     */
    public void requestGetAppList(){
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request = new Request.Builder()
                .url(String.format("http://tianze1688.com/api/index.php/news/user/getRedpack?osversion=7.1.2&sign=d78fd1c819662088eb9f699fd266dd6d&versionCode=18&adCode=18&from_uid=5&timesc=1557217128587&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=7"))
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if (TextUtils.isEmpty(result)) return;
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    String data=jsonObject.optString("data");
                    Gson gso=new Gson();




                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            List<Redpackmodel.DataBean> applist=gso.fromJson(data,new TypeToken<List<Redpackmodel.DataBean>>(){}.getType());
                            appLists.addAll(applist);
                            LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getBaseActivity());
                            rel_list.setLayoutManager(linearLayoutManager);
                            appListAdater=new RedpackAdater(getActivity(),appLists);
                            rel_list.setAdapter(appListAdater);
                            appListAdater.setOnItemClickListener(new RedpackAdater.OnRecyclerViewItemClickListener() {
                                @Override
                                public void onItemClick(View view, int data) {

                                    Glide.with(getBaseActivity()).load(applist.get(data).getWcphoto()).asBitmap().into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                                        @Override
                                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                            int imageWidth = resource.getWidth();
                                            int imageHeight = resource.getHeight();
                                            int height = ScreenUtils.getScreenWidth(getBaseActivity()) * imageHeight / imageWidth;
                                            ViewGroup.LayoutParams para = iv_test.getLayoutParams();
                                            para.height = height;
                                            para.width = ScreenUtils.getScreenWidth(getBaseActivity());
                                            iv_test.setImageBitmap(resource);

                                            //一键功能截图
                                            String[] PERMISSIONS = {
                                                    "android.permission.READ_EXTERNAL_STORAGE",
                                                    "android.permission.WRITE_EXTERNAL_STORAGE" };
                                            //检测是否有写的权限
                                            int permission = ContextCompat.checkSelfPermission(getBaseActivity(),
                                                    "android.permission.WRITE_EXTERNAL_STORAGE");
                                            if (permission != PERMISSION_GRANTED) {
                                                // 没有写的权限，去申请写的权限，会弹出对话框
                                                ActivityCompat.requestPermissions(getBaseActivity(), PERMISSIONS,1);
                                            }
                                            //创建savephoto类保存图片
                                            SavePhoto savePhoto = new SavePhoto(getBaseActivity());
//                                        savePhoto.SaveBitmapFromView(iv_test);
// 缩小图片
                                            Matrix matrix = new Matrix();
                                            matrix.postScale(0.5f,0.5f); //长和宽放大缩小的比例
                                            resource = Bitmap.createBitmap(resource,0,0,resource.getWidth(),resource.getHeight(),matrix,true);
                                            DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                                            saveBitmap(resource,resource.toString() + ".JPEG");
                                            Toast.makeText(getBaseActivity(), "截图成功保存到相册", Toast.LENGTH_SHORT).show();
                                        }
                                    });




//                                    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "zhangphil.jpg");
//                                    Bitmap bitmap = screenShot(getBaseActivity());
//                                    try {
//                                        if (!file.exists())
//                                            file.createNewFile();
//
//                                        boolean ret = save(bitmap, file, Bitmap.CompressFormat.JPEG, true);
//                                        if (ret) {
//                                            Toast.makeText(getBaseActivity(), "截图已保持至 " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
//                                        }
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
                                }
                            });
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 保存图片到文件File。
     *
     * @param src     源图片
     * @param file    要保存到的文件
     * @param format  格式
     * @param recycle 是否回收
     * @return true 成功 false 失败
     */
    public static boolean save(Bitmap src, File file, Bitmap.CompressFormat format, boolean recycle) {
        if (isEmptyBitmap(src))
            return false;

        OutputStream os;
        boolean ret = false;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            ret = src.compress(format, 100, os);
            if (recycle && !src.isRecycled())
                src.recycle();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ret;
    }


    /**
     * 获取当前屏幕截图，不包含状态栏（Status Bar）。
     *
     * @param activity activity
     * @return Bitmap
     */
    public static Bitmap screenShot(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int statusBarHeight = getStatusBarHeight(activity);
        int width = (int) getDeviceDisplaySize(activity)[0];
        int height = (int) getDeviceDisplaySize(activity)[1];

        Bitmap ret = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();

        return ret;
    }

    public static float[] getDeviceDisplaySize(Context context) {
        Resources resources = context.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        int width = dm.widthPixels;
        int height = dm.heightPixels;

        float[] size = new float[2];
        size[0] = width;
        size[1] = height;

        return size;
    }

    public static int getStatusBarHeight(Context context) {
        int height = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = context.getResources().getDimensionPixelSize(resourceId);
        }

        return height;
    }

    /**
     * Bitmap对象是否为空。
     */
    public static boolean isEmptyBitmap(Bitmap src) {
        return src == null || src.getWidth() == 0 || src.getHeight() == 0;
    }
    /*
     * 保存文件，文件名为当前日期
     */
    public void saveBitmap(Bitmap bitmap, String bitName){
        String fileName ;
        File file ;
        if(Build.BRAND .equals("Xiaomi") ){ // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/"+bitName ;
        }else{ // Meizu 、Oppo
            Log.v("qwe","002");
            fileName = Environment.getExternalStorageDirectory().getPath()+"/DCIM/"+bitName ;
        }
        file = new File(fileName);
        if(file.exists()){
            file.delete();
        }
        FileOutputStream out;
        try{
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if(bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out))
            {
                out.flush();
                out.close();
                // 插入图库
                MediaStore.Images.Media.insertImage(getBaseActivity().getContentResolver(), file.getAbsolutePath(), bitName, null);
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        // 发送广播，通知刷新图库的显示
        getBaseActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
    }
    public class SavePhoto{
        //存调用该类的活动
        Context context;
        public SavePhoto(Context context) {
            this.context = context;
        }
        //保存文件的方法：
        public void SaveBitmapFromView(View view) throws ParseException {
            int w = view.getWidth();
            int h = view.getHeight();
            Bitmap bmp = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(bmp);
            view.layout(0, 0, w, h);
            view.draw(c);
            // 缩小图片
            Matrix matrix = new Matrix();
            matrix.postScale(0.5f,0.5f); //长和宽放大缩小的比例
            bmp = Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true);
            DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            saveBitmap(bmp,bmp.toString() + ".JPEG");
        }
        /*
         * 保存文件，文件名为当前日期
         */
        public void saveBitmap(Bitmap bitmap, String bitName){
            String fileName ;
            File file ;
            if(Build.BRAND .equals("Xiaomi") ){ // 小米手机
                fileName = Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/"+bitName ;
            }else{ // Meizu 、Oppo
                Log.v("qwe","002");
                fileName = Environment.getExternalStorageDirectory().getPath()+"/DCIM/"+bitName ;
            }
            file = new File(fileName);
            if(file.exists()){
                file.delete();
            }
            FileOutputStream out;
            try{
                out = new FileOutputStream(file);
                // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
                if(bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out))
                {
                    out.flush();
                    out.close();
                    // 插入图库
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), bitName, null);
                }
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            // 发送广播，通知刷新图库的显示
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
        }
    }
}
